<?php
session_start();
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Account Controller
 * @package  CMS
 * @author Vui Nguyen - 09/04/2013 
 * @link http://joomlavui.info
 */
class Account extends CI_Controller {
    
    function __construct() {
        parent::__construct();
        $this->load->library('session');
		$this->load->library('smarty3');
		$this->load->library('session');
		$this->smarty			= new CI_Smarty3();
		// load models user,billing
		$this->load->model('kpay/db_user_model');
        $this->db_user_model		= new db_user_model();
        $this->load->model('kpay/db_card_model');
        $this->db_card_model = new db_card_model();
	$this->load->library('pay/login_service');
        
        require_once APPPATH . '../library/captcha/securimage.php';
    }

    //---------------------------------------------------------------------
    // ------------------------- HOME -------------------------------------
    function index() {
        $user = $this->session->userdata('user_info');
        if(!$user)
        {
            redirect('account/login');
        }
        
        // trans history
        $data['page'] = 1;
        $data['limit'] = 20;
        $data['total'] = count($this->db_card_model->getCardLogByCustomerID($user[0]->customerID));
        
        $data['numpage'] = round($data['total']/$data['limit']);
        if($data['numpage']*$data['limit']<$data['total'])
            $data['numpage']+=1;

        $data['trans_history'] = $this->db_card_model->getCardLogByCustomerID_2($user[0]->customerID, $data['page'], $data['limit']);
        
        foreach($data['trans_history'] as $item)
        {
            switch($item->typeUse)
            {
                case 'muathe':
                    $item->serialNumber = explode('@', $item->serialNumber);
                    $item->cardNumber = explode('@', $item->cardNumber);
                    $item->typeUse = 'Mua Thẻ';
                    break;
                case 'bantien':
                    $item->typeUse = 'Bắn Tiền';
                    break;
            }
        }
        
        
        //update session
        $this->_update_user_info($user);
        
        //user info tab
        $this->info();
        
        //secret question tab
        $this->change_secret_questions();
        
        $this->smarty->assign('menu','account');
        $this->smarty->assign(array('user_info'=>$user, 'data'=>$data));
        $this->smarty->view('template/pages_live/account_info','content');
        $this->smarty->view('template/pages_live/partner','partner');
        $this->smarty->display('template/frontend_live/home');
    }
    
    //-----------------------------------------------------------------------
    //------------------------ UPDATE PASSWORD OPENID -----------------------
    function update_pass()
    {
        $user = $this->session->userdata('user_info');
        if(!$user)
        {
            redirect('account/login');
        }
        $flag = $this->session->userdata('first_time_login_by_OID');
        
        if($flag)
        {
            $this->smarty->assign('user_info',$user);
            $this->smarty->view('template/pages_live/update_password','content');
            $this->smarty->display('template/frontend_live/home');
        }
        else{
            redirect('account');
        }
    }
    
    //---------------------------------------------------------------------
    //------------------------ ADD SUB-PHONE-NUMBER -----------------------
    function list_phone_number()
    {
        $user = $this->session->userdata('user_info');
        if(!$user)
        {
            redirect('account/login');
        }
        
        $user = $this->db_user_model->getUserByCustomerID($user[0]->customerID);
        $PhoneNumberArray['main'] = $user[0]->phoneNumber;
        $subPhoneNumber = $this->db_user_model->getUserExtraByCustomerID($user[0]->customerID);
        if($subPhoneNumber[0]->subphonenumber!='')
        {
            $PhoneNumberArray['sub'] = explode(',', $subPhoneNumber[0]->subphonenumber);
        }
        
        $this->smarty->assign('user_info', $user);
        $this->smarty->assign('phoneNumber', $PhoneNumberArray);
        $this->smarty->view('template/frontend/list_phone_number','info');
        $this->smarty->display('template/frontend/home');
    }
    
    //---------------------------------------------------------------------
    //---------------------- CHANGE SECRET QUESTIONS ----------------------
    function change_secret_questions()
    {
        //$user = $this->session->userdata('user_info');
        //if(!$user)
        //{
        //    redirect('account/login');
        //}
        
//        if($_POST)
//        {
//            $ques_1 = $this->input->post('question-1');
//            $ques_2 = $this->input->post('question-2');
//            $ans_1 = $this->input->post('answer-1');
//            $ans_2 = $this->input->post('answer-2');
//            
//            $questions = $ques_1.";".$ques_2;
//            $answers = $ans_1.";".$ans_2;
//            
//            //inser db
//            $aParams = array(
//                "customerID"=>$user[0]->customerID,
//                "questions"=>$questions,
//                "answers"=>$answers
//            );
//            $aUpdate = array("customerID","questions","answers");
//            $this->db_user_model->insert_onduplicate_update_UserExtra($aParams, $aUpdate);
//            $this->smarty->assign('success',1);
//        }
        
        //lấy danh sách câu hỏi bí mật
        $questions = array();
        
        $doc1 = new DOMDocument();
        $doc1->load( APPPATH.'../db/01_secret_question.xml' );
        $danh_sach = $doc1->getElementsByTagName( "cau_hoi" );
        foreach( $danh_sach as $ds ) 
        { 
            $cauhoi = $ds->getElementsByTagName( "noi_dung" );
            $questions[1][] = $cauhoi->item(0)->nodeValue;
        }
        
        $doc2 = new DOMDocument();
        $doc2->load( APPPATH.'../db/02_secret_question.xml' );
        $danh_sach = $doc2->getElementsByTagName( "cau_hoi" );
        foreach( $danh_sach as $ds ) 
        { 
            $cauhoi = $ds->getElementsByTagName( "noi_dung" );
            $questions[2][] = $cauhoi->item(0)->nodeValue;
        }
        
        //$this->smarty->assign('user_info', $user);
        $this->smarty->assign('questions', $questions);
        //$this->smarty->view('template/frontend/secret_question','info');
        //$this->smarty->display('template/frontend/home');
    }
    
    //---------------------------------------------------------------------
    //---------------------- FORGOT PASSWORD ------------------------------
    function getpassword()
    {
        $securimage = new Securimage();
        $msgs = array();
        $errMsg = '';

        if($_GET){
            if($this->input->get('verify_step')=='1')
            {
                $step = $this->input->get('verify_step');
                $this->smarty->assign('step',1);
            }  else {
                show_404();
            }
        }
        else
            $this->smarty->assign('step',0);
        
        if($_POST)
        {
            $step = $this->input->post('verify_step');
            if($step == 1) //xác nhận code
            {
                $expire = time()-$this->session->userdata('expire');
                if($expire>3600)
                {
                    //insert verify code into db
                    $aParams = array(
                        'customerID'=>$this->session->userdata('customerID'),
                        'verifycode'=> ''
                    );
                    $aUpdate = array("customerID","verifycode");
                    $this->db_user_model->insert_onduplicate_update_UserExtra($aParams, $aUpdate);
                }
                
                $confirmCode = $this->input->post('verifycode');
                $newPassword = $this->input->post('newpassword');
                
                if($newPassword == '')
                    $msgs[] = 'Chưa nhập mật khẩu mới';
                if($confirmCode == '')
                    $msgs[] = 'Chưa nhập code xác nhận';
                else
                {
                    $isCodeExist = $this->db_user_model->check_verify_code($confirmCode);
                    if($isCodeExist!=1)
                        $msgs[] = 'Code xác nhận không đúng';
                }
                
                if(count($msgs)==0)
                {
                    //$newPassword = random_string('alpha');
                    $email = $this->session->userdata('email');
                    $customerID = $this->session->userdata('customerID');
                    $result = $this->login_service->resetPassword($email, $customerID, $newPassword);
                    if($result['code'] < 0)
                    {
                        $msgs[] = $result['msg'];
                        $this->smarty->assign('step', 1);
                    }
                    else{
                        $mail_to = $email;
                        $mail_tilte = 'Mua Thẻ Vn Supply Password';
                        $mailcontent = '';
                        $mailcontent .= "Cảm ơn bạn đã sử dụng dịch vụ Mua Thẻ Vn. <br><br>";
                        $mailcontent .= "Mật khẩu mới cho tài khoản $email là: <b>$newPassword</b><br><br>";
                        $mailcontent .= "Nếu bạn muốn thay đổi mật khẩu vui lòng đăng nhập tại <a href='".  base_url() ."/account/login'>http://muathe.vn/account/login</a>.<br><br>";
                        $mailcontent .= "Mọi thắc mắc hoặc cần hỗ trợ vui lòng gửi về mail: support@muathe.vn";      

                        sendMail($mail_to, $mail_tilte, $mailcontent);
                        
                        $succMsg = ' Reset mật khẩu thành công.';
                        $this->smarty->assign('step', 2);
                        $this->smarty->assign('succMsg',$succMsg);
                    }
                }
            }
            else if($step == 0) //send mail step
            {
                $email = $this->input->post('email');
                $captcha = $this->input->post('captcha');


                //check email
                if($email == '')
                    $msgs[] = 'Chưa nhập email';
                elseif($this->login_service->checkEmail($email)==FALSE)
                    $msgs[] = 'Email không tồn tại';

                //check captcha
                if($captcha == '')
                    $msgs[] = 'Chưa nhập mã xác nhận';
                elseif(!$securimage->check($captcha) && $captcha!==false)
                    $msgs[] = 'Mã xác nhận không đúng';

                if(count($msgs)==0)
                {
                    $verifyCode = random_string('alpha', 5);

                    $mail_to = $email;
                    $mail_tilte = 'Mua Thẻ Vn Confirm Reset Password';
                    $mailcontent = '';
                    $mailcontent .= "Chào bạn! <br><br>";
                    $mailcontent .= "Bạn vừa gửi yêu cầu lấy lại mật khẩu cho tài khoản $email tại <a href='#'>Muathẻ.vn</a><br><br>";
                    $mailcontent .= "Chúng tôi sẽ cung cấp cho bạn mã xác nhận để chứng thực bạn là chủ tài khoản trên.<br><br>";
                    $mailcontent .= "Mã xác nhận: <b style='color:red;'>$verifyCode</b><br><br>";
                    $mailcontent .= "Vào <a href='".base_url()."account/getpassword?verify_step=1'>đây</a> để nhập mật khẩu mới.";

                    $mailconfirm = sendMail($mail_to,$mail_tilte, $mailcontent);
                    
                    if($mailconfirm){
                        $succMsg = 'Vui lòng check email để lấy mã xác nhận, thông tin chỉ có hiệu lực trong vòng 1 giờ.';
                        $this->smarty->assign('step', 1);
                        $this->smarty->assign('succMsg',$succMsg);

                        //insert verify code into db
                        $user = $this->db_user_model->getUserByEmail($email);
                        $aParams = array(
                            'customerID'=>$user[0]->customerID,
                            'verifycode'=> $verifyCode
                        );
                        $aUpdate = array("customerID","verifycode");
                        $this->db_user_model->insert_onduplicate_update_UserExtra($aParams, $aUpdate);
                        
                        //set session user info
                        $this->session->set_userdata(array('email'=>$user[0]->email,'customerID'=>$user[0]->customerID));
                    }else
                        $msgs[] = 'Lỗi mail, không gửi được yêu cầu';
                    
                    $this->session->set_userdata('expire',time());
                }
            }
            foreach($msgs as $m)
            {
                $errMsg .= "$m.<br/>";
            }

            
            $this->smarty->assign('errMsg',$errMsg);
        }
        
        $this->smarty->view('template/pages_live/getpassword','content');
        $this->smarty->display('template/frontend_live/home');
    }
    
    //---------------------------------------------------------------------
    //---------------------- TRANSACTION HISTORY --------------------------
    function trans_history()
    {
        $user = $this->session->userdata('user_info');
        if(!$user)
        {
            redirect('home');
        }
        
        $this->smarty->assign('user_info', $this->session->userdata('user_info'));

        $this->smarty->view('template/frontend/history','info');
        $this->smarty->display('template/frontend/home');
    }
    
    //---------------------------------------------------------------------
    //---------------------- USER INFORMATION -----------------------------
    function info(){
        $user = $this->session->userdata('user_info');
        if(!$user)
        {
            redirect('home');
        }        
        $user_info = $this->db_user_model->getUserByCustomerID($user[0]->customerID);
        $this->smarty->assign('user_info', $this->_update_user_info($user_info));
        //$this->smarty->view('template/frontend/info','info');
        //$this->smarty->display("template/frontend/home");
    }
    
    //---------------------------------------------------------------------
    //---------------------- CHANGE PASSWORD ------------------------------
    function changepass()
    {
        $user = $this->session->userdata('user_info');
        if(!$user)
        {
            redirect('account/login');
        }
        
        $securimage = new Securimage();
        
        if(!empty($_POST))
        {
            $Password   = $_POST['Password'];
            $newPassword = $_POST['newPassword'];
            $re_newPassword = $_POST['re_newPassword'];
            $captcha = $_POST['captcha'];
            //echo $Password.'-'.$newPassword.'-'.$re_newPassword;exit;
            $msg = array();
            if($Password == '')
                $msg[] = 'Mật khẩu cũ không được bỏ trống';
            if($newPassword == '')
                $msg[] = 'Mật khẩu mới không được bỏ trống';
            if($re_newPassword == '')
                $msg[] = 'Mật khẩu xác nhận không được bỏ trống';
            if($re_newPassword != $newPassword)
                $msg[] = 'Mật khẩu xác nhận không khớp mật khẩu mới';
            if(!$securimage->check($captcha) && $captcha!==false)
                $msg[] = 'Mã xác nhận không đúng';
            
            $errMsg = '';
            if(count($msg)==0)
            {
                $result = $this->login_service->changePassword($user[0]->email, $Password, $newPassword, $user[0]->customerID);
                if($result['code'] < 0)
                {
                    $msg[] = $result['msg'];
                }
                else{
                    $user = json_decode($result['msg']);
                    //$this->session->set_userdata('user_info', $user_info);
                    $this->smarty->assign("changepass", TRUE);
                }
            }
            
            foreach($msg as $m)
            {
                $errMsg .= "$m.<br/>";
            }
            $this->smarty->assign('errMsg',$errMsg);
            
        }
        
            $this->smarty->assign('user_info', $user);
            $this->smarty->view('template/frontend_live/changepass','info');
            $this->smarty->display('template/frontend_live/home');
        
    }
    
    //---------------------------------------------------------------------
    //----------------------------- LOGIN ---------------------------------
    function login() {
        $user = $this->session->userdata('user_info');
        $errMsg = '';
        if(!$user)
        {
            if($_POST){
            $email = $this->input->post('email');
            $password = $this->input->post('password');
            $msg = array();
            if($email !='' && $password != '')
            {
                // call function login
                $resultLogin = $this->login_service->login($email, $password);//print_r($resultLogin);exit;              
                if($resultLogin['code']<0)
                {
                    $msg[] = $resultLogin['msg'];
                    if(is_array($resultLogin))
                    {
                        
                        foreach($msg as $m)
                        {
                            $errMsg .= $m."<br/>";
                        }
                        $this->smarty->assign('errMsg', $errMsg);
                    }
                    
                }
                else
                {
                    $user_info = json_decode($resultLogin['msg']);
                    //print_r($user_info);exit;
                    //update last login
                    $aParams = array(
                        'customerID'=>$user_info[0]->customerID,
                        'lastlogin'=> date("Y-m-d H:i:s")
                    );
                    $aUpdate = array("customerID","lastlogin");
                    $this->db_user_model->insert_onduplicate_update_User($aParams, $aUpdate);
                    
                    $this->_update_user_info($user_info);
                    $this->session->set_userdata('user_info', $user_info);
                    $this->smarty->assign("user_info", $user_info);
                    redirect('home');
                }
            }else
            {
                if($email=='')
                    $errMsg.='Chưa nhập email<br/>';
                if($password=='')
                    $errMsg.='Chưa nhập mật khẩu<br/>';
                $this->smarty->assign('errMsg', $errMsg);
            }
            }
        }
        else {
            $user_info = $this->session->userdata('user_info');
            $this->smarty->assign("user_info", $user_info);
        }
        //$this->change_secret_questions();
        $this->smarty->view('template/pages_live/partner','partner');
        $this->smarty->view('template/pages_live/login','content');
        $this->smarty->display("template/frontend_live/home");
    }
    
    //---------------------------------------------------------------------
    //-------------------------- REGISTER ---------------------------------
    function register() {
        
        $securimage = new Securimage();
        
            $email = $this->input->post('email');
            $password = $this->input->post('password');
            $captcha = $this->input->post('captcha');
        if($email != '' || $password != '' || $captcha != ''){
            $msg=array();

            if (!$password || strlen($password) < 6) {
                $code = -1;
                $msg[] = "Mật khẩu quá ngắn (trên 5 ký tự).";
            }
            if (preg_match("/^[0-9a-zA-Z]\w+(\.\w+)*\@\w+(\.[0-9a-zA-Z]+)*\.[a-zA-Z]{2,4}$/", $email) === 0) {
                $code = -1;
                $msg[] = "Email không hợp lệ hoặc chưa đúng định dạng.";
            }
            if (strlen($password) >= 6) {
                if ($password == $email)
                    $msg[] = "Mật khẩu không được trùng với Tài khoản.";
            }
            if (!$securimage->check($captcha) && $captcha!==false) {
                $code = -1;
                $msg[] = "Mã xác nhận không đúng.";
            }

            $errMsg = '';
            
            if(count($msg)==0)
            {
                $result = $this->login_service->register($email, $password);
                //print_r($result);
                if($result['code'] < 0)
                {
                    $msg[] = $result['msg'];
                }
                else{
                    $user_info = json_decode($result['msg']);
                    //insert update user extra table
                    $aParams = array(
                        "customerID"=>$user_info[0]->customerID
                    );
                    $aUpdate = array("customerID");
                    $this->db_user_model->insert_onduplicate_update_UserExtra($aParams, $aUpdate);
                    
                    $this->session->set_userdata('user_info', $user_info);
                    $this->smarty->assign("user_info", $user_info);
                }
            }
            foreach($msg as $m)
            {
                $errMsg .= "$m.<br/>";
            }
            $this->smarty->assign('errMsg',$errMsg);
        }  
        
        $this->smarty->view('template/frontend/register','form');
        $this->smarty->display('template/frontend/home');
    }
    
    //---------------------------------------------------------------------
    //---------------------- CHECK EMAIL EXIST ----------------------------
    function check_email()
    {
        $email = $this->input->post('email');
        
        echo $this->login_service->checkEmail($email);
    }
    
    //---------------------------------------------------------------------
    //---------------------------- LOGOUT ---------------------------------
    function logout() {
        //$this->login_service->logout();
        $this->session->sess_destroy();
        session_destroy();
        redirect('home');
    }

    //---------------------------------------------------------------------
    //------------------ UPDATE SESSION USER INFO -------------------------
    function _update_user_info(&$userinfo)
    {
        $userextra = $this->db_user_model->getUserExtraByCustomerID($userinfo[0]->customerID);
        if($userextra)
			$userinfo[0]->cmnd = $userextra[0]->cmnd;
		else
			$userinfo[0]->cmnd = "";	
        //return $userinfo;
    }
}

/* End of file account.php */
/* Location: ./application/controllers/account.php */